package com.example.file.service;

import com.example.common.entity.LoginUser;
import com.example.common.exception.BizException;
import com.example.common.exception.errcode.ErrCodeFile;
import com.example.common.result.PageResult;
import com.example.common.utils.BeanUtils;
import com.example.common.utils.IdUtils;
import com.example.file.dao.SysFileDao;
import com.example.file.dao.SysFileRepository;
import com.example.file.entity.po.SysFile;
import com.example.file.entity.query.FileQuery;
import com.example.file.entity.vo.SysFileVo;
import com.example.file.utils.FileNameUtils;
import com.example.file.utils.FileUnitUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Cleanup;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class FileService {
    @Resource
    private IdUtils idUtils;
    @Resource
    private SysFileRepository sysFileRepository;
    @Resource
    private SysFileDao sysFileDao;
    @Resource
    private LoginUser loginUser;

    public SysFileVo insertFile(MultipartFile file) {
        //todo 查询数据库启用何种方式保存文件,1本地保存,2阿里云OSS,3腾讯云,4百度云,5七牛云等

        String filename = file.getOriginalFilename();   //文件名
        SysFile sysFile = SysFile.builder()
                .fileId(idUtils.nextId())
                .fileName(filename)
                .prefixName(FileNameUtils.getPrefixName(filename))
                .suffixName(FileNameUtils.getSuffixName(filename))
                .fileType(file.getContentType())
                .fileSize(file.getSize())
                .url("")    //todo url
                .status(1)
                .createTime(LocalDateTime.now())
                .createUser(loginUser.getUserId() + "")
                .build();
        sysFileRepository.save(sysFile);

        SysFileVo sysFileVo = BeanUtils.facade().map(sysFile, SysFileVo.class);

        sysFileVo.setFileSize(FileUnitUtils.fileSize2Human(sysFile.getFileSize()));
        return sysFileVo;
    }

    public void deleteFileById(Long fileId) {
        SysFile sysFile = SysFile.builder()
                .fileId(fileId)
                .status(0)
                .updateTime(LocalDateTime.now())
                .build();
        sysFileRepository.save(sysFile);
    }

    public SysFileVo selectFileInfoByFileId(Long fileId) {
        Optional<SysFile> optional = sysFileRepository.findById(fileId);
        if (optional.isPresent()) {
            SysFileVo sysFileVo = BeanUtils.facade().map(optional.get(), SysFileVo.class);
            sysFileVo.setFileSize(FileUnitUtils.fileSize2Human(optional.get().getFileSize()));
            return sysFileVo;
        }
        return new SysFileVo();
    }

    public PageResult selectFileInfoList(FileQuery fileQuery) {
        PageHelper.startPage(fileQuery.getPage(), fileQuery.getRows());

        List<SysFile> list = sysFileDao.selectFileInfoList(fileQuery);
        PageInfo<SysFile> pageInfo = new PageInfo<>(list);

        List<SysFileVo> sysFileVos = BeanUtils.facade().mapAsList(pageInfo.getList(), SysFileVo.class);
        sysFileVos.forEach(i -> {
            i.setFileSize(FileUnitUtils.fileSize2Human(Long.valueOf(i.getFileSize())));
        });
        return PageResult.result(pageInfo.getTotal(), sysFileVos);
    }

    public void selectFileBinary(Long fileId, HttpServletResponse resp) throws IOException {
        Optional<SysFile> optional = sysFileRepository.findById(fileId);
        if (!optional.isPresent()) {
            throw new BizException(ErrCodeFile.FILE_NOT_FOUND); //文件不存在
        }
        SysFile sysFile = optional.get();

        File file = new File("C:\\Users\\wen\\Pictures\\1.png");

        if (!file.exists()) {
            throw new BizException(ErrCodeFile.FILE_NOT_FOUND); //文件不存在
        }

        // 根据 HttpServletResponse 获得输出流
        ServletOutputStream os = resp.getOutputStream();

        resp.setContentType("application/octet-stream;charset=utf-8");    // 设置ContentType
        // 设置文件名
        String fileName = new String(sysFile.getFileName().getBytes("GB2312"), "ISO8859_1");
        //String fileName = URLEncoder.encode("ViewData","UTF-8");
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);


        @Cleanup FileInputStream fis = new FileInputStream(file);
        int len = 0;
        while ((len = fis.read()) != -1) {
            os.write(len);
        }
    }
}
